#include"compressOutput_cpu.h"
#include"compressTitle_cpu.h"

void full_size_decompress(char* fileName, char* outFileName, char* ref)
{
	FILE* fin = fopen(fileName,"rb");
	if(fin == NULL)
		printf("cant open %s", fileName);
	FILE* fout = fopen(outFileName, "w");
	
	uint32 titleCount;
	uint32 max_title_size;
	uint32 queryLen;
	
	fread(&titleCount, sizeof(int), 1, fin);
	fread(&max_title_size, sizeof(int), 1, fin);
	fread(&queryLen, sizeof(int), 1, fin);

	printf("titleCount:%u\n", titleCount);	
	printf("max_title_size:%u\n", max_title_size);	
	printf("queryLen:%u\n", queryLen);	
	
	INIT_TIMER;
	START_TIMER;

	char* titleBuffer = (char*)malloc(titleCount * max_title_size);
	decompressTitle(fin, titleBuffer, titleCount, max_title_size);

	END_TIMER;
	PRINT_TIMER_SEC("decompress title: ");

	uint32 dataSize = 0;
	uint32 blockSize = 0;
	h_result* outputBuffer = NULL;
	uint32 resultSize = 0, totalSize = 0;
	fread(&dataSize, sizeof(int), 1, fin);

	while(totalSize < dataSize) {
		totalSize += decompressResult(&outputBuffer,&resultSize, fin);
		print_full_size_result_cpu(outputBuffer, resultSize, fout, titleBuffer, max_title_size, ref, queryLen);
		free(outputBuffer);
	}

	fclose(fin);
	fclose(fout);	
}

#define MAX_REF_LENGTH (2858012806)

int main(int argc, char* argv[])
{
	char* fileName = argv[1];
	char* outFileName = argv[2];
	char* refFile = argv[3];
	FILE* inRef = fopen(refFile, "r");
	if(inRef == NULL) 
		printf("cant open file: %s\n", refFile);
	char* ref = (char*)malloc((uint64)MAX_REF_LENGTH);
	fread(ref,1,(uint64)MAX_REF_LENGTH, inRef);
	
	
	INIT_TIMER;
	START_TIMER;	

	full_size_decompress(fileName, outFileName,ref);	
	
	END_TIMER;
	PRINT_TIMER_SEC("decompress time:");
	free(ref);
	fclose(inRef);
	return 0;
}
